package com.red.wood.module.questionnaire.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.red.wood.common.util.CommonUtils;
import com.red.wood.common.util.IMap;
import com.red.wood.module.questionnaire.service.QuestionnaireService;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/questionnaireOper")
public class QuestionnaireOperController {

	private static final Log log = LogFactory.getLog(QuestionnaireOperController.class);
	
	@Autowired
	private QuestionnaireService service;
	
	/**
	 * 调查问卷
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("questionnaireOper");
		String referer = request.getHeader("Referer");
		if(StringUtils.isBlank(referer)) {
			mv = new ModelAndView("error");
		}
		return mv;
	}
	
	
	/**
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "insert", method = RequestMethod.POST)
	@ResponseBody
	public String questionnaireOper(HttpServletRequest request, HttpServletResponse response) {
		JSONObject json = new JSONObject();
		try {
			IMap map = new IMap(request);
			
			List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String daytime = sdf.format(new Date());
			
			String companyStr = CommonUtils.valueOf(map.remove("key"));
			String[] companysStr =  companyStr.split("&");
			
			Map<String,Object> companys = new HashMap<String,Object>();
			for(int i = 0 ; i < companysStr.length ; i++) {
				String name = companysStr[i].split("=")[0];
				String value = companysStr[i].split("=")[1];
				companys.put(name, value);
			}
			
			for(Map.Entry<String,Object> entry : map.entrySet()) {
				String values = CommonUtils.valueOf(entry.getValue());
				
				String[] valuesStr = values.split("&");
				Map<String,Object> datas = new HashMap<String,Object>();
				int yesNum = 0;//统计是的个数
				for(int i = 0 ; i < valuesStr.length ; i++) {
					String name = valuesStr[i].split("=")[0];
					String value = valuesStr[i].split("=")[1];
					if(StringUtils.startsWith(name, "question") && StringUtils.equals(value, "是")) {
						yesNum++;
					}
					datas.put(name, value);
				}
				datas.put("daytime",daytime);
				datas.put("yesNum",yesNum);
				datas.put("noNum", 22-yesNum);
				datas.putAll(companys);
				
				list.add(datas);
			}
			
			
			//校验，判断公司和厂商是否已经填写
			//首先判断是否重复填写厂商
			Set<String> set = new HashSet<String>();
			for(Map<String,Object> datas : list) {
				set.add(datas.get("companyName")+"-->"+datas.get("tradeName"));
			}
			if(set.size() != list.size()) {
				//表示厂商有重复填写
				json.put("flag", false);
				json.put("msg","信安系统建设厂商名称有重复填写，请核查！");
				return json.toString();
			}
			//进一步判断，判断数据库是否已经填写相同公司名称和厂商
			for(Map<String,Object> datas : list) {
				String companyName = CommonUtils.valueOf(datas.get("companyName"));
				String tradeName = CommonUtils.valueOf(datas.get("tradeName"));
				
				boolean flag = service.questionnaireOperCheck(companyName, tradeName);
				if(flag) {//表示数据库已经存在
					json.put("flag", false);
					json.put("msg","厂商名称【"+tradeName+"】和单位名称【"+companyName+"】已经填写过！");
					return json.toString();
				}
			}
			service.questionnaireOper(list);
			json.put("flag", true);
		} catch (Exception e) {
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
			json.put("flag",false);
		}
		return json.toString();
	}
}